package com.java1412.web.interceptor.admin;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.java1412.common.utils.R;
import com.java1412.common.utils.ResponseEnum;
import com.java1412.web.utils.JWTUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author java1412
 * @since 2025-05-20 14:39
 */
@Component
public class JWTInterceptor implements HandlerInterceptor {
    @Resource
    private JWTUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        R r = null;
        // 获取请求头中的token
        String token = request.getHeader("token");
        try {
            DecodedJWT decodedJWT = jwtUtil.verify(token);
            // r = R.r(ResponseEnum.JWT_VERIFY_SUCCESS);
            return true;
        } catch (SignatureVerificationException e) {
            e.printStackTrace();
            r = R.r(ResponseEnum.JWT_SIGNATURE_VERIFICATION);
        } catch (TokenExpiredException e) {
            e.printStackTrace();
            r = R.r(ResponseEnum.JWT_TOKEN_EXPIRED);
        } catch (AlgorithmMismatchException e) {
            e.printStackTrace();
            r = R.r(ResponseEnum.JWT_ALGORITHM_MISMATCH);
        } catch (Exception e) {
            e.printStackTrace();
            r = R.r(ResponseEnum.JWT_TOKEN_INVALID);
        }
        // 不放行之前需要将判断jwt的信息以json返回给浏览器
        ObjectMapper om = new ObjectMapper();
        String json = om.writeValueAsString(r);
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}
